#include <arch/memory.h>

uint32_t BackTrace(void **buffer, uint32_t size)
{
    int i = 0;
    int n = 0;
    uint32_t _ebp = 0;
    uint32_t _eip = 0;

    //get EBP register value
    __asm__ __volatile__("movl %%ebp,%0"
                         : "=g"(_ebp)::"memory");

    for (i = 0, n = 0; i < size && _ebp != 0 && *(uint32_t *)_ebp != 0 && *(uint32_t *)_ebp != _ebp; i++, n++)
    {
        //caller address
        _eip = (uint32_t)((uint32_t *)_ebp + 1);
        _eip = *(uint32_t *)_eip;
        //last called stack point
        _ebp = *(uint32_t *)_ebp;
        buffer[i] = (void *)_eip;
    }
    return n;
}
